<script setup>
import IconSimple from '@/components/icon-simple/index.vue'
import {chooseImage, previewImage, uploadFile} from '@/utils/uni-api-wrap/media'
import to from 'await-to-js'
import {tip} from '@/utils/uni-api-wrap/toast'
import {isJsonObjectsEqual} from '@/utils/utils'

const props = defineProps({
  modelValue: {
    type: Array,
    default: () => ([])
  },
  maxlength: {
    type: Number,
    default: -1
  }
})

const emit = defineEmits(['update:modelValue'])

const imageList = ref([...props.modelValue])

watch(props, newProps => {
  if (newProps.modelValue.length !== imageList.value.length) {
    imageList.value = [...newProps.modelValue]
  }
})

watch(imageList, newList => {
  emit('update:modelValue', newList)
})

const upload = async () => {
  const [err, [result]] = await to(chooseImage())
  if (err) return tip('没有访问权限')
  const [uploadErr, uploadResult] = await to(uploadFile(result.tempFilePath))
  if (uploadErr) return tip(uploadErr.message)
  imageList.value = [...imageList.value, { tempFilePath: result.tempFilePath, url: uploadResult }]
}

const preview = item => {
  previewImage([item.tempFilePath])
}

const clear = index => {
  imageList.value = imageList.value.filter((_, idx) => idx !== index)
}
</script>

<template>
  <view class="pics-container">
    <view class="upload-result-box" v-for="(item,index) in imageList" :key="index" @click="preview(item)">
      <view class="clear-icon" @click.stop.prevent>
        <uni-icons type="clear" color="#fff" size="30" @click.stop.prevent="clear(index)"></uni-icons>
      </view>
      <image :src="item.url" mode="aspectFill" />
    </view>
    <view class="upload-box flex-col" v-if="props.maxlength === -1 || imageList.length < props.maxlength" @click="upload">
      <icon-simple name="camera" />
      <view>添加照片</view>
    </view>
  </view>
</template>

<style scoped lang="scss">
.pics-container {
  display: flex;
  flex-direction: row;
  flex-wrap: wrap;
  image, .upload-result-box, .upload-box {
    display: inline-block;
    flex: 0 0 218rpx;
    margin-bottom: 16rpx;
    margin-right: 16rpx;
    width: 218rpx;
    height: 218rpx;
    border-radius: 16rpx;
    overflow: hidden;
    &:nth-of-type(3n) {
      margin-right: 0;
    }
  }
  .upload-result-box {
    position: relative;
    .clear-icon {
      position: absolute;
      right: 12rpx;
      top: 12rpx;
    }
  }
  .upload-box {
    box-sizing: border-box;
    text-align: center;
    border: 2rpx solid $kaoyan-color-12;
    margin: 0;
    icon-simple {
      display: inline-block;
      margin-top: 66rpx;
    }
    view {
      margin-top: 8rpx;
      @include fs28w600($kaoyan-color-9);
    }
  }
}
</style>
